package com.rop.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rop.model.system.SysUser;
import com.rop.result.ResultCodeEnum;
import com.rop.system.custom.CustomerUser;
import com.rop.system.exception.BizException;
import com.rop.system.service.SysMenuService;
import com.rop.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Title: UserDetailsServiceImpl
 * @Author Rop
 * @Date 2023/5/12 11:49
 * @description:
 */

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUser sysUser = sysUserService.getBaseMapper().selectOne(wrapper);

        if (Objects.isNull(sysUser)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 用户已停用
        if (Objects.equals(sysUser.getStatus(), 0)) {
            BizException.error(ResultCodeEnum.ACCOUNT_STOP.getCode(), ResultCodeEnum.ACCOUNT_STOP.getMsg());
        }

        List<String> userButtonList = sysMenuService.getUserButtonList(Long.valueOf(sysUser.getId()));
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        for (String perm : userButtonList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }

        return new CustomerUser(sysUser, authorities);
    }
}
